<!--  -->
<template>
  <div class="process-container">
    <div class="table__wrapper">
      <transition :enter-active-class="this.animate.searchAnimate.enter" :leave-active-class="this.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="68px">
            <el-form-item label="数据源" prop="dataName">
              <el-select v-model="queryParams.dataName" filterable clearable placeholder="请选择/输入数据源名称" style="width: 200px">
                <el-option key="" label="全部" value="" />
                <el-option v-for="item in dataNameList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表名称" prop="tableName">
              <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="表描述" prop="tableComment">
              <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间" style="width: 418px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
      <div class="table-operates">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" icon="el-icon-download" @click="handleGenTable()" v-hasPermi="['tool:gen:code']">生成</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" size="mini" icon="el-icon-upload" @click="openImportTable" v-hasPermi="['tool:gen:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" size="mini" icon="el-icon-edit-outline" :disabled="single" @click="handleEditTable()" v-hasPermi="['tool:gen:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['tool:gen:remove']">
              删除
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tableList" height="100%" @selection-change="handleSelectionChange" class="common-table">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="50" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据源" align="center" prop="dataName" :show-overflow-tooltip="true" />
        <el-table-column label="表名称" align="center" prop="tableName" :show-overflow-tooltip="true" />
        <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" />
        <el-table-column label="实体" align="center" prop="className" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="预览" placement="top">
              <el-button type="text" icon="el-icon-view" @click="handlePreview(scope.row)" v-hasPermi="['tool:gen:preview']"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button type="text" icon="el-icon-edit-outline" @click="handleEditTable(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tool:gen:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="同步" placement="top">
              <el-button type="text" icon="el-icon-refresh" @click="handleSynchDb(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="生成代码" placement="top">
              <el-button type="text" icon="el-icon-download" @click="handleGenTable(scope.row)" v-hasPermi="['tool:gen:code']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 预览界面 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="(key).substring((key).lastIndexOf('/') + 1, (key).indexOf('.vm'))"
          :name="(key).substring((key).lastIndexOf('/') + 1, (key).indexOf('.vm'))"
          :key="value"
        >
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="copyTextSuccess" style="float:right">复制</el-link>
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
  </div>
</template>

<script>
import { listTable, previewTable, delTable, genCode, synchDb, getDataNames } from '@/api/tool/gen';
import ImportTable from './importTable.vue';

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
      ImportTable
    },
    data() {
      //这里存放数据
      return {
        tableList:[],
        loading:true,
        showSearch:true,
        ids: [],
        single: true,
        multiple: true,
        total: 0,
        dateRange: ['', ''],
        uniqueId: "",
        dataNameList: [],
        queryParams:{
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          tableComment: '',
          dataName: ""
        },
        preview:{
          data: {},
          activeName: 'domain.java'
        },
        dialog:{
          visible: false,
          title: '代码预览'
        }
      };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      const time = this.route.query.t;
      if (time != null && time != this.uniqueId) {
        this.uniqueId = time;
        this.queryParams.pageNum = Number(this.route.query.pageNum);
        this.dateRange = ['', ''];
        this.$refs.queryFormRef?.resetFields();
        this.getList();
      }
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.getList();
      this.getDataNameList();
    },
    //方法集合
    methods: {
      /** 查询多数据源名称 */
      async getDataNameList() {
        const res = await getDataNames()
        this.dataNameList = res.data;
      },

      /** 查询表集合 */
      async getList() {
        this.loading = true;
        const res = await listTable(this.addDateRange(this.queryParams, this.dateRange));
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 生成代码操作 */
      async handleGenTable(row){
        const tbIds = row?.tableId || this.ids;
        if (tbIds == "") {
          this.$modal.msgError('请选择要生成的数据');
          return;
        }
        if (row?.genType === "1") {
          await genCode(row.tableId);
          this.$modal.msgSuccess('成功生成到自定义路径：' + row.genPath);
        } else {
          this.$download.zip('/tool/gen/batchGenCode?tableIdStr=' + tbIds, 'ruoyi.zip');
        }
      },
      /** 同步数据库操作 */
      async handleSynchDb(row) {
        const tableId = row.tableId;
        await this.$modal.confirm('确认要强制同步"' + row.tableName + '"表结构吗？');
        await synchDb(tableId);
        this.$modal.msgSuccess('同步成功');
      },
      /** 打开导入表弹窗 */
      openImportTable() {
        this.$refs.importRef?.show(this.queryParams.dataName);
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = ['', ''];
        this.$refs.queryFormRef?.resetFields();
        this.handleQuery();
      },
      /** 预览按钮 */
      async handlePreview(row) {
        const res = await previewTable(row.tableId);
        this.preview.data = res.data;
        this.dialog.visible = true;
        this.preview.activeName = 'domain.java';
      },
      /** 复制代码成功 */
      copyTextSuccess() {
        console.log("复制======>")
        this.$modal.msgSuccess('复制成功');
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.tableId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 修改按钮操作 */
      handleEditTable(row) {
        const tableId = row?.tableId || this.ids[0];
        this.$router.push({ path: '/tool/gen-edit/index/' + tableId, query: { pageNum: this.queryParams.pageNum } });
      },
      /** 删除按钮操作 */
      async handleDelete(row) {
        const tableIds = row?.tableId || this.ids;
        await this.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？');
        await delTable(tableIds);
        await this.getList();
        this.$modal.msgSuccess('删除成功');
      }
    },
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类

</style>